<script setup lang="ts">
import type { Rules } from 'async-validator';
import { useAsyncValidator } from '@vueuse/integrations/useAsyncValidator';

const route = useRoute();
const router = useRouter();

const loginUser = useLoginUserStore();
const notification = useNotificationStore();

const isLogin = computed(() => route.path === '/login');
const formData = reactive({ username: '', email: 'swk@hgs.com', password: '123123', confirmPassword: '' });

const rules = () => {
  let rules: Rules = {
    username: [
      {
        required: true,
        message: '请输入用户名',
      },
      {
        min: 4,
        max: 16,
        message: '最小长度为4个字符，最大长度为16个字符',
      },
      {
        pattern: /^[a-zA-Z]+[a-zA-Z0-9_]*$/,
        message: '用户名必须以字母开头，可以包含数字和_',
      },
    ],
    email: [
      {
        type: 'email',
        message: '请检查电子邮件是否正确',
      },
      {
        required: true,
        message: '请输入电子邮件',
      },
    ],
    password: [
      {
        required: true,
        message: '请输入密码',
      },
      {
        min: 6,
        message: '最小长度为6个字符',
      },
    ],
    confirmPassword: [
      {
        required: true,
        message: '请确认密码',
      },
      {
        validator(rule, value, callback, source) {
          if (value != '' && value !== source.password) {
            callback('两次输入的密码不一致');
          } else {
            callback();
          }
        },
      },
    ],
  };
  if (isLogin.value) {
    rules = {
      email: [
        {
          type: 'email',
          message: '请检查电子邮件是否正确',
        },
        {
          required: true,
          message: '请输入电子邮件',
        },
      ],
      password: [
        {
          required: true,
          message: '请输入密码',
        },
        {
          min: 6,
          message: '最小长度为6个字符',
        },
      ],
    };
  }
  return rules;
};

const url = computed(() => {
  if (isLogin) {
    return 'users/login';
  } else {
    return 'users/signup';
  }
});

const { pass, errorFields } = useAsyncValidator(formData, rules);
const { execute } = useFetch(url, { immediate: false }).post(formData);

const submitHandler = () => {
  if (isLogin.value) {
    execute()
      .then((res) => res.json())
      .then((json) => {
        loginUser.login(json);

        notification.addNotice({
          id: Date.now(),
          message: '欢迎回来',
          status: 'success',
        });

        router.push('/user');
      })
      .catch(() => {
        notification.addNotice({
          id: Date.now(),
          message: '电子邮件或者密码错误',
          status: 'warning',
          duration: 5000,
        });
      });
  }
};
</script>

<template>
  <div class="auth">
    <BackButton></BackButton>

    <h2>
      <template v-if="isLogin"> 您好，欢迎回来！ </template>
      <template v-else> 欢迎加入</template>
    </h2>

    <form @submit.prevent="submitHandler">
      <FormInput :error="errorFields?.username" v-model.trim="formData.username" v-show="!isLogin" type="text" lable="请输入用户名"></FormInput>
      <FormInput :error="errorFields?.email" v-model.trim="formData.email" type="text" lable="请输入邮箱"></FormInput>
      <FormInput :error="errorFields?.password" v-model.trim="formData.password" type="password" lable="请输入密码" toggle></FormInput>
      <FormInput
        :error="errorFields?.confirmPassword"
        v-model.trim="formData.confirmPassword"
        v-show="!isLogin"
        type="password"
        lable="请确认密码"
        toggle
      ></FormInput>

      <p>
        <template v-if="isLogin">没有账号？<router-link to="/signup">注册</router-link></template>
        <template v-else>已有账号！<router-link to="/login">登录</router-link></template>
      </p>
      <BottomButton :disabled="!pass">
        <template v-if="isLogin">登录</template>
        <template v-else>注册</template>
      </BottomButton>
    </form>
  </div>
</template>

<style lang="scss" scoped>
.auth {
  padding: 40rem 20rem 0;

  h2 {
    font-size: 30rem;
  }

  p {
    font-size: 16rem;
    a {
      color: var(--hilight-color);
    }
  }
}
</style>
